#include "client.h"
#include <func.h>
#define SERVER_IP "127.0.0.1"   //服务器的IP地址
#define SERVER_PORT 8080        //服务器的端口号

void userRegister(int sockfd){
    char request[256]={0};
    char username[128]={0};
    char password[128]={0};

    printf("Enter username for registration:");
    scanf("%s",username);

    printf("Enter password for registration:");
    scanf("%s",password);
    
    //封装成火车头再发
    train_t t;
    memset(&t,0,sizeof(t));
    t.type = REQUEST;
    snprintf(t.buff,sizeof(t.buff),"%s %s\n",username,password);
    printf("t.buff:%sover\n",t.buff);
    t.len = strlen(t.buff);
    sendn(sockfd,&t,t.len+8);


    handleResponse(sockfd);
}

int main()
{
    int clientfd = tcpConnect(SERVER_IP, SERVER_PORT);

    //用户注册操作
    char choice;
    printf("Do you want to register a new account?(y/n):");
    scanf(" %c",&choice);//注意前面的空格，确保正确读取字符
    if(choice == 'y'||choice == 'Y'){
        userRegister(clientfd);

    }

    //用户登录er操作
    userLogin(clientfd);

    char buf[128] = {0};
    //4. 使用select进行监听
    fd_set rdset;
    train_t t;
    while(1) {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(clientfd, &rdset);
        
        int nready = select(clientfd + 1, &rdset, NULL, NULL, NULL);
        printf("nready:%d\n", nready);
        if(FD_ISSET(STDIN_FILENO, &rdset)) {
            //读取标准输入中的数据
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            if(0 == ret) {
                printf("byebye.\n");
                break;
            }
            memset(&t, 0, sizeof(t));
            //解析命令行
            buf[strlen(buf)-1] = '\0';
            parseCommand(buf, strlen(buf), &t);
            sendn(clientfd, &t, 4 + 4 + t.len);
            if(t.type == CMD_TYPE_PUTS) {
                putsCommand(clientfd, &t);
            }
        } else if(FD_ISSET(clientfd, &rdset)) {
            recv(clientfd, buf, sizeof(buf), 0);
            printf("recv:%s\n", buf);
        }
    }
    close(clientfd);
    return 0;
}

